<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人资料</h2>
        </div>
      </template>
      
      <el-form 
        ref="profileForm" 
        :model="profileData" 
        :rules="rules" 
        label-width="100px"
        label-position="right"
        status-icon
      >
        <div class="avatar-container">
          <el-avatar :size="100" :src="profileData.avatar || defaultAvatar" />
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleAvatarChange"
          >
            <el-button type="primary" size="small">更换头像</el-button>
          </el-upload>
        </div>
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileData.username" disabled />
        </el-form-item>
        
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="profileData.realName" />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="profileData.phone" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileData.email" />
        </el-form-item>
        
        <el-form-item label="部门" prop="department">
          <el-input v-model="profileData.department" />
        </el-form-item>
        
        <el-form-item label="职位" prop="position">
          <el-input v-model="profileData.position" />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-tag v-for="role in profileData.roles" :key="role" class="role-tag">{{ role }}</el-tag>
        </el-form-item>
        
        <el-form-item label="最后登录">
          <span>{{ profileData.lastLogin }}</span>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 默认头像
const defaultAvatar = new URL('../../assets/avatar.png', import.meta.url).href

// 表单引用
const profileForm = ref(null)

// 个人资料数据
const profileData = reactive({
  username: 'admin',
  realName: '管理员',
  phone: '13800138000',
  email: 'admin@tms.com',
  department: '信息技术部',
  position: '系统管理员',
  roles: ['超级管理员'],
  lastLogin: '2025-03-20 13:45:30',
  avatar: ''
})

// 表单验证规则
const rules = {
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  department: [
    { max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
  ],
  position: [
    { max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
  ]
}

// 加载用户数据
const loadUserProfile = () => {
  // 这里应该从API获取用户数据，目前使用模拟数据
  console.log('加载用户资料')
  // 实际项目中应该调用API获取用户信息
  // const { data } = await getUserProfile()
  // Object.assign(profileData, data)
}

// 处理头像变更
const handleAvatarChange = (file) => {
  // 限制文件类型和大小
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
    return
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return
  }

  // 读取文件为base64
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    profileData.avatar = reader.result
  }
}

// 提交表单
const submitForm = async () => {
  if (!profileForm.value) return
  
  await profileForm.value.validate(async (valid) => {
    if (valid) {
      try {
        // 这里应该调用API保存用户资料
        // await updateUserProfile(profileData)
        ElMessage.success('个人资料更新成功')
      } catch (error) {
        console.error('更新个人资料失败:', error)
        ElMessage.error('个人资料更新失败')
      }
    } else {
      return false
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!profileForm.value) return
  profileForm.value.resetFields()
  // 重新加载用户资料
  loadUserProfile()
}

// 组件挂载时加载用户资料
onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.avatar-uploader {
  margin-top: 15px;
}

.role-tag {
  margin-right: 8px;
}
</style>
